<?php
/**
 * 自动催款机
 * 每月5号、8号、11号自动检索本月未还款的用户,并发送短信提醒其还款
 * 15号在自动检索一次,还未还款的,发短信给当地客户经理
 *
 * @author mr2longly
 */

namespace Console\Controller;

use Common\Library\Constant;
use Think\Log;
use Common\Library\SendSMS;

class RepaymentReminderController extends CronController
{

    private $_repaymentDate = '';
    private $_repaymentTime = '';

    public function __construct()
    {
        parent::__construct();
        //固定还款日
        $this->_repaymentDate = date('Y-m-' . Constant::BILL_LAST_DAY);

        $this->_repaymentTime = strtotime($this->_repaymentDate);
    }

    /**
     * 每月7号、8号、9号，11号、20号自动检索本月未还款的用户,并发送短信提醒其还款
     * cron配置项: 0    0   5,8,11,15   *   *   php console.php /RepaymentReminder
     */
    public function index()
    {
        //$this->_runLog('测试测试测试测试测试测试测试测试测试测试'.time());
        //Log::write('测试测试测试测试测试测试测试测试测试测试'.time(), Log::INFO);

            //$customerInfo =  M('Customer')->where(['id' => 20])->field(['real_name', 'mobile'])->find();
            //print_r($customerInfo);
            //$file = fopen('/home/wwwroot/default/apitest/test.txt', 'a');
           // fwrite($file, json_encode($customerInfo).time()."\n");
           //SendSMS::waitReviewed('13520166164');
        //echo 111;exit;
        $this->searching7th();//还剩3天
        $this->searching8th();//还剩2天
        $this->searching9th();//还剩1天
        $this->searching11th();//逾期1天
        $this->searching20th();//逾期10天
        /*
        $date = date('d');
        //$date = '05';
        switch ($date) {
            case '07':
                $this->searching7th();//还剩3天
                break;
            case '08':
                $this->searching8th();//还剩2天
                break;
            case '09':
                $this->searching9th();//还剩1天
                break;
            case '11':
                $this->searching11th();//逾期1天
                break;
            case '20':
                $this->searching20th();//逾期10天
                break;
            default:
                $this->_runLog("执行时间错误:", Log::ERR);
                break;
        }
        */
    }

    public function searching7th()
    {
        $this->_runLog('07号催款:start');
        $repaymentTime = strtotime(date("Y-m-d",strtotime("+3 day")));
        $customerList = $this->_getUnpaidCustomerList($repaymentTime);
        if ($customerList) {
            $this->_smsReminder($customerList,7,$repaymentTime);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_runLog('07号催款:end');
    }

    public function searching8th()
    {
        $this->_runLog('08号催款:start');
        $repaymentTime = strtotime(date("Y-m-d",strtotime("+2 day")));
        $customerList = $this->_getUnpaidCustomerList($repaymentTime);
        if ($customerList) {
            $this->_smsReminder($customerList,8,$repaymentTime);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_runLog('08号催款:end');
    }

    public function searching9th()
    {
        $this->_runLog('09号催款:start');
        $repaymentTime = strtotime(date("Y-m-d",strtotime("+1 day")));
        $customerList = $this->_getUnpaidCustomerList($repaymentTime);
        if ($customerList) {
            $this->_smsReminder($customerList,9,$repaymentTime);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_runLog('09号催款:end');
    }

    public function searching11th()
    {
        $this->_runLog('11号催款:start');
        $repaymentTime = strtotime(date("Y-m-d",strtotime("-1 day")));
        $customerList = $this->_getUnpaidCustomerList($repaymentTime);
        if ($customerList) {
            $this->_smsReminder($customerList,11,$repaymentTime);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_runLog('11号催款:end');
    }
/*
    public function searching15th()
    {
        $this->_runLog('15号催款:start');

        $customerList = $this->_getUnpaidCustomerList();
        if ($customerList) {
            $this->_smsReminder($customerList,15);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_smsReminderAccountManager();

        $this->_runLog('15号催款:end');
    }
*/

    public function searching20th()
    {
        $this->_runLog('20号催款:start');
        $repaymentTime = strtotime(date("Y-m-d",strtotime("-10 day")));
        $customerList = $this->_getUnpaidCustomerList($repaymentTime);
        if ($customerList) {
            $this->_smsReminder($customerList,20,$repaymentTime);
        } else {
            $this->_runLog('oh! 本月没有消费订单');
        }

        $this->_smsReminderAccountManager();

        $this->_runLog('20号催款:end');
    }


    private function _getUnpaidCustomerList($repaymentTime)
    {
        // 取本月有账单的用户列表包括次月还+分期还
        $needRepayList = array_merge(
            $this->_getNextMonthRepayList($repaymentTime),
            $this->_getInstallmentRepayList($repaymentTime)
        );

        $monthBill = [];
        foreach ($needRepayList as $row) {
            $customerId = $row['customer_id'];
            $sumAmount  = $row['sum_amount'];
            $sumAllAmount  = $row['sum_all_amount'];
            if ($sumAmount <= 0) {
                continue;
            }

            if (isset($monthBill[$customerId])) {
                $monthBill[$customerId] += array('sumAmount'=>$sumAmount,'sumAllAmount'=>$sumAllAmount);
            } else {
                $monthBill[$customerId] = array('sumAmount'=>$sumAmount,'sumAllAmount'=>$sumAllAmount);
            }
        }

        $this->_runLog('本月未还款用户结果', Log::INFO);
        $this->_runLog($monthBill, 'Result');
        return $monthBill;
    }

    /**
     * 取还款类型:[次月还] 未还款消费者消费列表
     * @return array
     */
    private function _getNextMonthRepayList($repaymentTime)
    {
        $sql = "SELECT SUM(a.amount) as sum_amount, a.customer_id,SUM(a.amount) as sum_all_amount FROM consume_history a left join customer b on (a.customer_id = b.id) 
            WHERE a.type =1 AND a.status =1 AND a.repayment_time ='$repaymentTime' AND b.type =1 
            GROUP BY a.customer_id";
        //echo $sql;
        $nextMonthRepay = M()->query($sql);

        $this->_runLog($sql, Log::SQL);
        $this->_runLog($nextMonthRepay, 'Result');

        return $nextMonthRepay && is_array($nextMonthRepay) ? $nextMonthRepay : [];
    }


    /**
     * 取还款类型:[分期还] 未还款消费者消费列表
     * @return array
     */
    private function _getInstallmentRepayList($repaymentTime)
    {
        $sql = "SELECT SUM(installment.amount) AS sum_amount, history.customer_id,SUM(history.amount) as sum_all_amount FROM `consume_history` history 
            LEFT JOIN consume_installment_history installment ON installment.parent_id=history.id  
            LEFT JOIN customer cus on history.customer_id = cus.id 
            WHERE history.type in(2,5) AND history.status in (1,4) AND installment.status =0 AND installment.`repayment_time` ='$repaymentTime' AND cus.type =1 
            GROUP BY history.customer_id";
        //echo $sql;
        $installmentRepay = M()->query($sql);

        $this->_runLog($sql, Log::SQL);
        $this->_runLog($installmentRepay, 'Result');

        return $installmentRepay && is_array($installmentRepay) ? $installmentRepay : [];
    }

    private function _smsReminder($customerList,$day,$repaymentTime)
    {
        $Customer = M('Customer');
        foreach ($customerList as $customerId => $consumeAmount) {
            $customerInfo = $Customer->where(['id' => $customerId])->field(['real_name', 'mobile','birthplace','type'])->find();
            if (!$customerInfo) {
                $this->_runLog("用户ID:{$customerId} 未查询到用户信息", Log::ERR);
                continue;
            }

            if (empty($customerInfo['mobile'])) {
                $this->_runLog("用户ID:{$customerId} 未查询到用户手机号", Log::ERR);
            } elseif (!is_mobile($customerInfo['mobile'])) {
                $this->_runLog("用户ID:{$customerId} 预留的手机号不是合法的手机号", Log::ERR);
            }

            $message = sprintf(
                '亲爱的%s，您本月账单已出，应还金额%.2f元，最后还款日%s',
                empty($customerInfo['real_name']) ? '用户' : $customerInfo['real_name'],
                fen2yuan($consumeAmount['sumAmount']),
                $this->_repaymentDate
            );
            $this->_runLog($message, Log::INFO);

            //Todo 掉短信接口发短信
            $mobile = $customerInfo['mobile'];
            $birthplace = $customerInfo['birthplace'];
            $type = $customerInfo['type'];
            $phone_arr= array(
                'luanxian'=>13473551011,
                'qianan'=>13393051576
            );
            if(strpos($birthplace,'迁安')!==false) {
                $key = 'qianan';
            }elseif(strpos($birthplace,'滦县')!==false) {
                $key = 'luanxian';
            }else{
                $key = 'qianan';
            }
            $phone = $phone_arr[$key];

            $days='';
            $overdue_amount = '';
            if($day==20) {
                $days = 10;
                $overdue_amount = fen2yuan(ceil($consumeAmount['sumAllAmount']*0.003*$days));
            }
            $repaymentDate = ($repaymentTime>0) ? date('Y-m-d',$repaymentTime) : $this->_repaymentDate;
            //echo $mobile.' '.$customerInfo['real_name'].' '.fen2yuan($consumeAmount['sumAmount']).' '.$overdue_amount.' '.$repaymentDate.' '.$day."\n";
            SendSMS::smsReminder($mobile,$customerInfo['real_name'],fen2yuan($consumeAmount['sumAmount']),$repaymentDate,$phone,$days,$overdue_amount,$day);
        }
        //echo '+++';
        //SendSMS::smsReminder('13520166164','测试短信('.date('Y-m-d').')','100',$repaymentDate,$phone,$days,$overdue_amount,$day);
    }

    private function _smsReminderAccountManager()
    {
    }
}
